package com.yueyang.sojourn.server.service.kafka;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yueyang.sojourn.server.model.po.ShareData;
import com.yueyang.sojourn.server.service.share.ShareDataService;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.KafkaHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * 监听外部系统的分销行为数据
 */
@Component
@Slf4j
public class ShareDataListener {
    @Autowired
    private ShareDataService shareDataService;

    @KafkaListener(topics = "sojourn-share-data-01")
    public void listen(ConsumerRecord<?, ?> record, @Header(KafkaHeaders.RECEIVED_TOPIC) String topic) {
        log.info("Receive： +++++++++++++++ Topic:" + topic);
        log.info("Receive： +++++++++++++++ Record:" + record);
        //判断是否NULL
        Optional<?> kafkaMessage = Optional.ofNullable(record.value());

        if (kafkaMessage.isPresent()) {
            String message = (String) kafkaMessage.get();
            //获取消息
            log.info("Receive： +++++++++++++++ Message:" + message);
            JSONObject jsonMessage = JSON.parseObject(message);
            ShareData shareData = JSON.toJavaObject(jsonMessage, ShareData.class);
            this.shareDataService.actionForMessage(shareData);
        }
    }
}
